package com.pro01.backend.mapper;

import com.pro01.backend.pojo.UserPoint;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserPointMapper {

    // 插入用户积分总表
    @Select("SELECT * FROM user_points WHERE user_id = #{userId}")
    UserPoint getByUserId(@Param("userId") Long userId);

    @Insert("""
    INSERT INTO user_points (user_id, current_points, total_earned_points, total_used_points)
    VALUES (#{userId}, 0, 0, 0)
""")
    int insertInitial(@Param("userId") Long userId);

    @Update("""
    UPDATE user_points
    SET current_points = current_points + #{points},
        total_earned_points = total_earned_points + #{points},
        last_updated = NOW()
    WHERE user_id = #{userId}
""")
    int addPoints(@Param("userId") Long userId, @Param("points") Integer points);

    /**
     * 下面是管理员接口
     */

    // 管理员查看所有用户积分
    @Select("""
    SELECT up.*, u.username
    FROM user_points up
    LEFT JOIN users u ON up.user_id = u.id
    ORDER BY up.current_points DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Map<String, Object>> selectAllUserPoints(@Param("offset") int offset,
                                                  @Param("pageSize") int pageSize);

    @Select("SELECT COUNT(*) FROM user_points")
    int countAllUserPoints();

    // 减积分
    @Update("""
    UPDATE user_points
    SET current_points = GREATEST(current_points - #{points}, 0),
        total_used_points = total_used_points + #{points},
        last_updated = NOW()
    WHERE user_id = #{userId}
""")
    int subtractPoints(@Param("userId") Long userId, @Param("points") Integer points);

    // 查看用户积分排行榜
    @Select("""
    SELECT u.username, up.current_points
    FROM user_points up
    LEFT JOIN users u ON up.user_id = u.id
    ORDER BY up.current_points DESC
    LIMIT 10
""")
    List<Map<String, Object>> getTop10ByPoints();

    // 获取用户当前排名
    @Select("""
    SELECT 1 + COUNT(*) AS `rank`
    FROM user_points
    WHERE current_points > (
        SELECT current_points FROM user_points WHERE user_id = #{userId}
    )
""")
    Integer getUserRank(@Param("userId") Long userId);


    // 获取用户当前积分
    @Select("SELECT current_points FROM user_points WHERE user_id = #{userId}")
    Integer getUserPoints(@Param("userId") Long userId);


}
